133. Clone Graph
Description
Solution
I uses two map to store the visited
and waiting
nodes, then BFS for the next node be copied.
Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
|
class Solution { unordered_map<int, Node*> visited; unordered_map<int, Node*> waited; public: Node* cloneGraph(Node* node) { if(node == nullptr) return node; queue<Node*> q; Node* root = new Node(node->val, node->neighbors); q.push(root); waited[root->val] = root; while(!q.empty()){ int size = q.size(); for(int i = 0; i < size; i++){ auto top = q.front(); q.pop(); for(int i = 0; i < top->neighbors.size(); i ++){ auto nbor = top->neighbors[i]; if(visited.find(nbor->val) == visited.end()){ Node *next = nullptr; if(waited.find(nbor->val) == waited.end()){ next = new Node(nbor->val, nbor->neighbors); waited[nbor->val] = next; }else next = waited[nbor->val]; top->neighbors[i] = next; q.push(top->neighbors[i]); }else{ top->neighbors[i] = visited[nbor->val]; } } visited[top->val] = top; waited.erase(top->val); } } return root; } };
|